import threading
from queue import Queue

# 判断一个数是否是质数
def is_prime(n):
    if n <= 1:
        return False
    if n <= 3:
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False
    i = 5
    while i * i <= n:
        if n % i == 0 or n % (i + 2) == 0:
            return False
        i += 6
    return True

# 线程工作函数
def find_primes(start, end, result_queue):
    print(f"Thread {threading.current_thread().name} checking numbers from {start} to {end}")
    for num in range(start, end):
        if is_prime(num):
            result_queue.put(num)
    print(f"Thread {threading.current_thread().name} finished.")

if __name__ == '__main__':
    # 创建队列用于存储结果
    prime_queue = Queue()
    
    # 定义要检查的范围和线程数量
    total_numbers = 10000
    num_threads = 5
    
    # 计算每个线程应该处理的数字范围
    ranges = [(i, min(i + total_numbers // num_threads, total_numbers)) 
              for i in range(1, total_numbers, total_numbers // num_threads)]
    
    # 创建并启动线程
    threads = []
    for idx, (start, end) in enumerate(ranges):
        thread = threading.Thread(target=find_primes, args=(start, end, prime_queue), name=f'Thread-{idx+1}')
        threads.append(thread)
        thread.start()
    
    # 等待所有线程完成
    for thread in threads:
        thread.join()
    
    # 收集结果
    primes = []
    while not prime_queue.empty():
        primes.append(prime_queue.get())
    
    # 打印结果
    print("Found {} prime numbers.".format(len(primes)))
    # 如果需要打印所有质数，取消下面这行的注释
    print(sorted(primes))